
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

package com.hlkj.pay.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hlkj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.LocalContext;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.logging.config.BodyReaderHttpServletRequestWrapper;
import com.hlkj.pay.app.openapi.IOpenApiAppService;
import com.hlkj.pay.common.CommonResultCode;
import com.hlkj.pay.common.constants.MqConstant;
import com.hlkj.pay.config.ExtRocketMQTemplate;
import com.hlkj.pay.dto.LocalMerchantRequest;
import com.hlkj.pay.infrastructure.model.common.RequestLogDO;
import com.hlkj.pay.vo.order.req.OrderCommonParamReq;

import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @data 2022/2/8 13:22
 */
@Component
@Slf4j
@Order(Integer.MIN_VALUE)
public class OpenApiInterceptor implements HandlerInterceptor {

    @Autowired
    private ExtRocketMQTemplate extRocketMQTemplate;

    @Autowired
    private IOpenApiAppService openApiAppService;

    private final MappingJackson2HttpMessageConverter errorHttpResponseConverter = new MappingJackson2HttpMessageConverter();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String servletPath = request.getServletPath();
        if (StringUtils.isBlank(servletPath)) {
            servletPath = request.getPathInfo();
        }
        log.info("openApiInterceptor:{}", servletPath);
        LocalMerchantRequest localMerchantRequest = new LocalMerchantRequest();
        // 获取请求参数
        BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
        String body = requestWrapper.getBodyStr();
        if (!org.springframework.util.StringUtils.hasText(body)) {
            ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
            this.errorHttpResponseConverter.write(CommonResult.error(CommonResultCode.PARAMETER_ERROR.getCode(), CommonResultCode.PARAMETER_ERROR.getMsg()),
                    MediaType.APPLICATION_JSON, httpResponse);
            LocalContext.destroy();
            log.error("没有接收到参数");
            return false;
        }
        OrderCommonParamReq orderCommonParamReq = null;
        try {
            orderCommonParamReq = JsonUtils.parseObject(body, OrderCommonParamReq.class);
            log.info("openapi params:{}",JsonUtils.toJsonString(orderCommonParamReq));
        }
        catch (Exception e) {
            log.error("参数解析错误:{}",e.getMessage());
            ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
            this.errorHttpResponseConverter.write(CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), e.getMessage()), MediaType.APPLICATION_JSON, httpResponse);
            LocalContext.destroy();
            return false;
        }
        localMerchantRequest.setParams(body);
        localMerchantRequest.setStartTime(System.currentTimeMillis());
        localMerchantRequest.setRequestId(orderCommonParamReq.getRequestId());
        localMerchantRequest.setRequestUrl(servletPath);
        localMerchantRequest.setRequestMethod(request.getMethod());
        localMerchantRequest.setVersion(orderCommonParamReq.getVersion());
        LocalContext.set(localMerchantRequest);
        CommonResult<Void> respCommonResult = openApiAppService.checkApp(orderCommonParamReq);
        if (!respCommonResult.isSuccess()) {
            ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
            this.errorHttpResponseConverter.write(CommonResult.error(respCommonResult.getCode(), respCommonResult.getMsg()), MediaType.APPLICATION_JSON, httpResponse);
            LocalContext.destroy();
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        LocalMerchantRequest localMerchantRequest = (LocalMerchantRequest) LocalContext.get();
        RequestLogDO requestLogDO = new RequestLogDO();
        requestLogDO.setCostTime(System.currentTimeMillis() - localMerchantRequest.getStartTime());
        requestLogDO.setSn(localMerchantRequest.getSn());
        requestLogDO.setSubSn(localMerchantRequest.getSubSn());
        requestLogDO.setAppId(localMerchantRequest.getMerchantAppDO().getAppId());
        requestLogDO.setChannelCode(localMerchantRequest.getChannelCode());
        requestLogDO.setProviderCode(localMerchantRequest.getProviderCode());
        requestLogDO.setMchChannelCode(localMerchantRequest.getMchChannelCode());
        requestLogDO.setRequestId(localMerchantRequest.getRequestId());
        requestLogDO.setRequestUrl(localMerchantRequest.getRequestUrl());
        requestLogDO.setRequestParams(localMerchantRequest.getParams());
        requestLogDO.setResponse(localMerchantRequest.getResponse());
        requestLogDO.setIp(localMerchantRequest.getIp());
        requestLogDO.setIpLocation(localMerchantRequest.getIpLocation());
        requestLogDO.setCreateTime(System.currentTimeMillis());
        try {
            extRocketMQTemplate.send(MqConstant.REQUEST_LOG_TOPIC, requestLogDO);
        }
        catch (Exception e) {
            log.error("请求参数记录失败:{}", e.getMessage());
        }
        LocalContext.destroy();
    }
}
